package cz.muni.fi.pa165.languageschool;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 * Entity representing Student
 *
 * @author Michal Fučík (395624) michal.fuca.fucik(at)gmail.com
 */
@Entity
@Table(name = "Person")
@XmlRootElement
public class Student extends Person implements Serializable {

    @ManyToMany
    @JoinTable(
            name = "STUD_LEC",
            joinColumns = {
                @JoinColumn(name = "STUD_ID", referencedColumnName = "PERSON_ID")},
            inverseJoinColumns = {
                @JoinColumn(name = "LEC_ID", referencedColumnName = "LECTURE_ID")})
    private List<Lecture> enrolledLectures = new ArrayList<>();

    // -- Methods --------------------------------------------------------------
    /**
     * Enrolled lectures property getter
     *
     * @return
     */
    @XmlTransient
    public List<Lecture> getEnrolledLectures() {
        return enrolledLectures;
    }

    /**
     * Enrolled lectures property setter
     *
     * @param ls
     */
    public void setEnrolledLectures(List<Lecture> ls) {
        this.enrolledLectures = ls;
    }

    /**
     * Enrolls to lecture and updates lecture's students list
     *
     * @param l
     */
    public void enroll(Lecture l) {
        this.enrolledLectures.add(l);
        if (!l.getEnrolledStudents().contains(this)) {
            l.getEnrolledStudents().add(this);
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj == this) {
            return true;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        final Student other = (Student) obj;
        if (this.getId() == null || !this.getId().equals(other.getId())) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += 13 * (getId() != null ? this.getId().hashCode() : 0);
        hash += 13 * getFirstName().hashCode();
        hash += 13 * getLastName().hashCode();
        return hash;
    }
}
